/*
描述：用户回答管理组件，用于展示和管理用户自己的回答，包括回答查看、删除等功能
完成人：吴悠
完成时间: 2025/04/27
*/


<script setup lang="ts">
import { ref, onMounted } from 'vue';
import axios, { AxiosError } from 'axios';
import RecentQuestion from "@/components/HomeView/RecentQuestion.vue";
import HeaderComponent from "@/components/HomeView/HeaderComponent.vue";
import MyNavbar from '@/components/UserView/MyNavbar.vue';
import {useRouter} from "vue-router";
import { ElMessageBox } from 'element-plus';
import QuestionComponent from "@/components/HomeView/QuestionComponent.vue";
const isLoggedIn = ref(false);
const userName = ref<string | null>(null);
const avatar = ref<string>('');


const router = useRouter();
const goQuestionDetailView = (questionId: number) => {
  router.push({
    path: '/question',
    query: { id: questionId }
  });
};

// 评论信息
interface Comment{
  id: number;
  content: string;
  createtime: string;
  like: number;
  user_id: number;
  question_id: number;
  title: string;
  img: string;
}
const comments = ref<Comment[]>([
  {
    id: 0,
    content: '',
    createtime: '',
    like: 0,
    user_id: 0,
    question_id: 0,
    title:'',
    img: ''

  }
]);


const formatDate = (dateString: string): string => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return date.toLocaleDateString('en-US', { month: 'long', day: 'numeric', year: 'numeric' }).toUpperCase();
};


const fetchCommentsInfo = async (): Promise<void> => {
  try {
    // Fetch comments
    const commentsResponse = await axios.get(
        'http://localhost:8089/comment/getComment',
        {
          headers: {
            'Content-Type': 'application/json',
            'Accept': '*/*'
          },
          params: { user_id:localStorage.getItem('id') }
        }
    );
    comments.value = commentsResponse.data.data;
  } catch (error) {
    const axiosError = error as AxiosError;
    console.error('Error fetching comments:', axiosError.message);
  }
};

const deleteComment = (id: number, user_id: number, question_id: number) => {
  ElMessageBox.confirm(
    '确定要删除这条回复吗？',
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      axios.request({
        method: 'DELETE',
        url: 'http://localhost:8089/comment/deleteComment',
        headers: {
          token: localStorage.getItem('token') || '',
          'Content-Type': 'application/json',
          'Accept': '*/*'
        },
        data: {
          id: id,
          user_id: user_id,
          question_id: question_id
        }
      }).then(() => {
        window.location.reload(); // 强制刷新页面（类似 F5）
      });
    })
    .catch(() => {
      // 用户取消删除操作
    });
}

onMounted(() => {
  isLoggedIn.value = !!localStorage.getItem('token');
  userName.value = localStorage.getItem('username');
  avatar.value = localStorage.getItem('avatar') || '';
  fetchCommentsInfo();
});
</script>
<template>
  <el-container>
    <HeaderComponent/>
    <el-container>
      <el-aside width="20%">
        <div class="sidebar-menu-left">
          <MyNavbar :now-page="2" />
        </div>
      </el-aside>
      <el-main class="body">
        <div
            v-for="(comment, index) in [...comments].reverse()"
            :key="index"
            class="comment-container"
        >
          <div class="comment-main-content">
            <div class="comment-content-wrapper" @click="goQuestionDetailView(comment.question_id)">
              <p class="comment-title">{{ comment.title }}</p>
              <div class="comment-header">
                <span class="comment-date"><el-icon><Calendar /></el-icon>{{ formatDate(comment.createtime) }}</span>
              </div>
              <p class="comment-content"><el-icon><ChatSquare /></el-icon>{{ comment.content }}</p>
            </div>
            <img :src="comment.img" alt="question img" class="comment-image">
          </div>
          <div class="comment-actions">
            <el-button
                type="danger"
                size="small"
                @click.stop="deleteComment(comment.id, comment.user_id, comment.question_id)"
                class="delete-button"
            >

              <span>删除回复</span>
            </el-button>
          </div>
        </div>
      </el-main>
      <el-aside width="20%">
        <div class="sidebar-menu-right">
          <RecentQuestion/>
        </div>
      </el-aside>
    </el-container>
  </el-container>
</template>
<style scoped>

*{
  background-color: #EEEEEE;
}

.login-prompt p {
  background-color: #FFFFFF;
  margin: 0;
}

.body {
  height: 100%;
  padding: 84px 20px 20px 20px;
  background-color: #F9FAFA;
}

.date .el-icon {
  background-color: #F9FAFA;
}

.logo span{
  background-color: white;
  margin-left: 7px;
  font-size: 20px;
  color: #BCBBBB;

}


.sidebar-menu-right {
  position: fixed;  /* 元素脱离文档流，相对于浏览器窗口固定定位 */
  top: 84px;
}


.likes-container .el-icon {
  background-color: #F9FAFA;
  color: #E7700D;
}


.comment-container {
  display: flex;
  flex-direction: column;
  gap: 15px;
  margin: 15px 0;
  padding: 15px;
  background-color: #FFFFFF;
  border: 1px solid #D6D9DC;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  position: relative;
}
.comment-title{
  background-color: white;
  font-size: 24px;
  font-weight: bold;
}
.comment-main-content {
  display: flex;
  gap: 20px;
  background-color: white;
}

.comment-content-wrapper {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8px;
  background-color: white;
  cursor: pointer;
}

.comment-image {
  width: 180px;
  height: 150px;
  object-fit: cover;
  border-radius: 4px;
  align-self: flex-start;
}

.comment-actions {
  display: flex;
  justify-content: flex-end;
  background-color: #FFFFFF;
  margin-top: 10px;
  padding-top: 10px;
  border-top: 1px solid #f0f0f0;
}

.delete-button {
  display: flex;
  align-items: center;
  gap: 5px;
}

.delete-button .el-icon {
  background-color: transparent;
}

.delete-button span {
  background-color: transparent;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  background-color: #FFFFFF;
}


.comment-date {
  margin-top: 4%;
  font-size: 16px;
  color: #666;
  background-color: #FFFFFF;
  display: flex;
  flex-direction: row;
  align-items: center;
}

.comment-content {
  font-size: 20px;
  line-height: 1.5;
  color: #333;
  margin: 0;
  background-color:white;
  display: flex;
  flex-direction: row;
  align-items: center;
}


.like-button .el-icon {
  font-size: 18px;
  background-color: #F9FAFA;
  transition: all 0.3s ease;
}

.like-button .liked {
  color: #E7700D;
  fill: #E7700D;
}



.comment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  background-color: #FFFFFF;
}

.body{
  height: 100%;
  padding: 64px 40px 20px 40px;
  background-color: #EEEEEE;
}

.sidebar-menu-left{
  display: flex;
  flex-direction: column;
  align-items: center;
  position: fixed;  /* 元素脱离文档流，相对于浏览器窗口固定定位 */
  top: 84px;
  height: 100vh;
  margin-left: 5%;
}
.sidebar-menu-right{
  display: flex;
  flex-direction: column;
  align-items: center;
  position: fixed;  /* 元素脱离文档流，相对于浏览器窗口固定定位 */
  top: 84px;
  height: 100vh;
}
</style>



